package com.qf.interceptor;

import com.qf.entity.Employee;
import com.qf.entity.Menu;
import org.springframework.stereotype.Component;
import org.springframework.web.servlet.HandlerInterceptor;
import org.springframework.web.servlet.ModelAndView;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.HttpSession;
import java.io.PrintWriter;
import java.util.List;

@Component
public class AuthInterceptor implements HandlerInterceptor {
    @Override
    public boolean preHandle(HttpServletRequest request, HttpServletResponse response, Object handler) throws Exception {
        String requestURI = request.getRequestURI();
        HttpSession session = request.getSession();
        Employee employee = (Employee) session.getAttribute("employee");
        List<Menu> menuList = employee.getRole().getMenuList();
        for (Menu menu : menuList) {
            if(requestURI.equals(menu.getUrl())){
                return true;
            }else{
                List<Menu> secondMenu = menu.getSecondMenu();
                for (Menu secondMenu1 : secondMenu) {
                    if(requestURI.equals(secondMenu1.getUrl())){
                        return true;
                    }
                }
            }
        }
        //判断是否是permission请求的地址
        List<Menu> permissionList = employee.getRole().getPermissionList();
        for (Menu menu : permissionList) {
            if(requestURI.equals(menu.getUrl())){
                return true;
            }
        }
        response.setContentType("text/html;charset=utf-8");
        PrintWriter writer = response.getWriter();
        writer.print("<script>location.href='/error.jsp'</script>");
        return false;
    }

    @Override
    public void postHandle(HttpServletRequest request, HttpServletResponse response, Object handler, ModelAndView modelAndView) throws Exception {

    }

    @Override
    public void afterCompletion(HttpServletRequest request, HttpServletResponse response, Object handler, Exception ex) throws Exception {

    }
}
